import { sendMobileCode } from '@/services/user'
import type { CodeType } from '@/types/user'
import { showSuccessToast, type FormInstance } from 'vant'
import { onUnmounted, ref, type Ref } from 'vue'

export const useMobileCode = (
  mobile: Ref<string>,
  type: CodeType = 'login'
) => {
  const time = ref(0)
  let timerId: number
  const form = ref<FormInstance>()
  const onSend = async () => {
    if (time.value > 0) return
    await form.value?.validate('mobile')
    await sendMobileCode(mobile.value, type)
    showSuccessToast('发送成功')
    time.value = 60
    clearInterval(timerId)
    timerId = window.setInterval(() => {
      time.value--
      if (time.value <= 0) window.clearInterval(timerId)
    }, 1000)
  }
  onUnmounted(() => {
    window.clearInterval(timerId)
  })

  return { onSend, time, form }
}
